<template>
  <div class="page-main" v-title data-title="物料领用权限维护表列表">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container">
      <div class="header">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :xl="{ span: 14 }" :lg="{ span: 11 }">
            <a-button class="hte-btn add-btn" type="primary" @click="handleAdd">创建</a-button>
            <a-button class="hte-btn" plain @click="handleEdit">编辑</a-button>
            <a-button class="hte-btn" @click="importExcelDataBtn"> <a-icon type="upload" /> 导入 </a-button>
            <a-button class="hte-btn" plain @click="handleExport">导出</a-button>
            <a-button class="hte-btn" plain @click="handleDel" style="color: red">删除</a-button>
            <a-button class="hte-btn" plain @click="handleReload">刷新</a-button>
          </a-col>
          <a-col :xl="{ span: 9 }" :lg="{ span: 13 }" class="input-ground">
            <a-input-group compact>
              <a-select v-model="pagination.type" style="width: 100px">
                <a-select-option value=""> 所有类型 </a-select-option>
                <a-select-option value="1"> 成本中心 </a-select-option>
                <a-select-option value="2"> WBS号 </a-select-option>
              </a-select>
              <a-input-search
                v-model="pagination.costNumber"
                @search="handleToSearch"
                placeholder="请按照关键字进行搜索"
              />
            </a-input-group>
            <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级搜索</a-button>
          </a-col>
        </a-row>
        <a-modal
          :visible="showSearchForm"
          width="70vw"
          :bodyStyle="{ padding: '10px' }"
          title="高级查询"
          @ok="handleToSearch"
          @cancel="showSearchForm = false"
        >
          <a-form-model
            ref="ruleForm"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            @keyup.enter.native="handleToSearch"
          >
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="费用类型">
                  <a-select v-model="pagination.type" style="width: 100%" allowClear>
                    <a-select-option value=""> 所有类型 </a-select-option>
                    <a-select-option v-for="(code, index) in typeOptions" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用号支出号">
                  <a-input allow-clear v-model="pagination.costNumber" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="领料人">
                  <a-input allow-clear v-model="pagination.consumUser" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-modal>
      </div>
      <div class="floatNav">
        <!-- <div class="budget-detail" @click="toMyTask">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge :offset="[-11, -15]">
            <p>我的报工单</p>
          </a-badge>
        </div> -->
        <!-- <div class="budget-detail">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge count="22" :offset="[-11, -15]">
            <p>验收付款单</p>
          </a-badge>
        </div> -->
      </div>
      <div class="content-list">
        <a-table
          :columns="columns"
          :data-source="records"
          rowKey="id"
          bordered
          :pagination="false"
          :customRow="customRow"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="typeRender" slot-scope="text, record">
            <template v-for="item in typeOptions">
              <template v-if="item.code == record.type">
                {{ item.name }}
              </template>
            </template>
          </template>
        </a-table>
        <a-pagination
          show-size-changer
          :default-current="1"
          :total="pagination.total"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
          :show-total="(total) => `共 ${total} 条记录`"
        />
      </div>
    </div>
    <LuckSheetPaste
      :title="'物料领用权限维护表批量导入'"
      ref="luckSheetPaste"
      :columnsExcel="columnsExcel"
      @handleOkExcel="handleOkExcel"
    ></LuckSheetPaste>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction, postAction } from '@/api/manage'
import { formatDate } from '@/utils/util'
import { uploadAction } from '@/api/manage'
import LuckSheetPaste from '@/components/excelPaste/LuckSheetPaste'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    LuckSheetPaste,
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        list: '/materials/powers/page',
        myPermission: '/workReport/project/myPermission',
        delete: '/materials/powers/delete',
        importExcleUrl: '/materials/powers/import',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      keywordType: '1',
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
        type: '',
      },
      typeOptions: [
        { code: '1', name: '成本中心' },
        { code: '2', name: 'WBS号' },
      ],
      records: [],
      columns: [
        {
          title: '费用类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'typeRender' },
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '费用支出号',
          dataIndex: 'costNumber',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '项目负责人',
          dataIndex: 'projectManager',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '领料人',
          dataIndex: 'consumUser',
          align: 'left',
          ellipsis: true,
        },
      ],
      columnsExcel: [
        {
          title: '费用类型',
          align: 'center',
          dataIndex: 'type',
        },
        {
          title: '费用支出号',
          align: 'center',
          dataIndex: 'costNumber',
        },
        {
          title: '领用人',
          align: 'center',
          dataIndex: 'consumUser',
        },
        {
          title: '项目名称',
          align: 'center',
          dataIndex: 'projectName',
        },
        {
          title: '项目经理',
          align: 'center',
          dataIndex: 'projectManager',
        },
        {
          title: '提示',
          align: 'center',
          dataIndex: 'tips',
        },
      ],
      showSearchForm: false,
      selectedRowKeys: [],
      selectedRows: [],
      permission: [],
    }
  },
  async mounted() {
    this.fetchList()
    this.fetchPermission()
  },
  methods: {
    formatDate,
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: '-1' }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      if (this.permission && powers) {
        for (let p of powers) {
          if (this.permission.indexOf(p) > -1) {
            hasPower = true
            break
          }
        }
      }
      return hasPower
    },
    handleToSearch() {
      this.pagination.pageNo = 1
      this.fetchList()
    },
    fetchList() {
      postAction(this.urls.list, this.pagination).then((res) => {
        if (res.success) {
          this.records = res.result.records
          this.$set(this.pagination, 'total', res.result.total)
        } else {
          this.$message.error('查询基建现场数据错误:' + res.message)
        }
      })
    },
    handleAdd() {
      let urlJump = this.$router.resolve({ path:'/materials/powers/add'})
      window.open(urlJump.href, '_blank')
    },
    handleEdit() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        return this.$message.warning('请选择一条记录操作')
      }
      let urlJump = this.$router.resolve({ path:'/materials/powers/edit/' + this.selectedRows[0].id})
      window.open(urlJump.href, '_blank')
    },
    handleDel() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        return this.$message.warning('请选择一条记录操作')
      }
      let applyNos = []
      for (let r of this.selectedRows) {
        applyNos.push(r.costNumber)
      }
      let that = this
      this.$confirm({
        content: `是否确定删除编辑物料领用权限维护表[${applyNos.join(',')}]？`,
        onOk: () => {
          getAction(that.urls.delete + '?id=' + that.selectedRowKeys.join(',')).then((res) => {
            if (res.success) {
              that.$message.success('删除成功')
              that.fetchList()
            } else {
              that.$message.error('删除失败:' + res.message)
            }
          })
        },
      })
    },
    handleReload() {
      this.fetchList()
    },
    handleExport() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      let url = process.env.VUE_APP_API_BASE_URL + '/materials/powers/export?token=' + token
      let searchForm = Object.assign({}, this.pagination)
      delete searchForm.total
      delete searchForm.pageNo
      delete searchForm.pageSize
      delete searchForm.sortField
      delete searchForm.sortOrder
      delete searchForm.pageSizeOptions
      for (var p in searchForm) {
        url += '&' + p + '=' + searchForm[p]
      }
      window.open(url)
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.pagination, 'pageSize', pageSize)
      this.$set(this.pagination, 'pageNo', pageNo)
      this.fetchList()
    },
    onShowSizeChange(pageNo, pageSize) {
      this.pagination.pageNo = 1
      this.pagination.pageSize = pageSize
      this.fetchList()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            if (!this.selectedRowKeys) {
              this.selectedRowKeys = []
              this.selectedRows = []
            }
            if (this.selectedRowKeys.indexOf(record.id) <= -1) {
              this.selectedRows.push(record)
              this.selectedRowKeys.push(record.id)
            } else {
              let index = this.selectedRowKeys.indexOf(record.id)
              this.selectedRowKeys.splice(index, 1)
              this.selectedRows.splice(index, 1)
            }
          },
        },
      }
    },
    importExcelDataBtn() {
      this.$refs.luckSheetPaste.showModalExcel()
    },
    async handleOkExcel(data) {
      let newData = []
      let pages = parseInt(data.length / 500)
      if (data) {
        let mode = data.length % 500
        if (mode > 0) {
          pages++
        }
      }
      for (let i = 0; i < pages; i++) {
        let subData = data.slice(i * 500, (i+1) * 500)
        let res = await postAction(this.urls.importExcleUrl, subData)
        if (res.code === 200) {
          this.$message.success('导入成功')
          newData = [...newData, ...res.result]
        } else {
          this.$message.warning('操作异常:' + res.message)
        }
      }
      this.$refs.luckSheetPaste.initByData(newData)
      this.fetchList()
    },
  },
  watch: {},
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .container {
    .content {
      margin-top: 20px;
      section {
        margin-bottom: 18px;
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
          /deep/ .a-upload__input {
            display: none !important;
          }
        }
      }
    }
  }
  .tips-box {
    margin-top: 32px;
    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}
/deep/ .el-upload__input {
  display: none !important;
}
</style>

